package com.fowo.api.datainterface.service.impl.implCore;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.fowo.api.datainterface.aspect.BaseAspect;
import com.fowo.api.datainterface.constants.DataTypeKind;
import com.fowo.api.datainterface.model.DataContextModel;
import com.fowo.api.datainterface.service.serviceCore.BaseFromService;
import com.fowo.api.datainterface.service.serviceCore.BaseInvokeService;
import com.fowo.api.datainterface.util.Common;
import com.fowo.api.datainterface.util.JScriptUtil;
import com.fowo.api.datainterface.util.JsonUtil;
import com.fowo.api.datainterface.util.RestUtilLingXing;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;

/**
 * 数据接口 服务实现类
 */
@Service
@Slf4j
@DS("ds24")
@RequiredArgsConstructor
public class LingxingServiceImpl implements BaseInvokeService, BaseFromService {

    private final Common common;
    private final RestUtilLingXing restUtilLingXing;
    private final JScriptUtil jScriptUtil;
    @Override
    public DataTypeKind getType() {
        return DataTypeKind.Lingxing;
    }

    @Override
    public JSONObject getAuth(DataContextModel.DatainterfaceAuthorityModel invoke)   {
        String appId = common.getAuthoritySimpleFactory(invoke, "appId");
        String appSecret = common.getAuthoritySimpleFactory(invoke, "appSecret");
        Assert.isTrue(ObjectUtil.isAllNotEmpty(appId, appSecret), "请配置授权格式,例: {\"appId\":\"\",\"appSecret\":\"\"}");
        JSONObject paramsAuth = new JSONObject();
        paramsAuth.put("appId", appId);
        paramsAuth.put("appSecret", appSecret);
        return paramsAuth;
//        //调用接口获取access-token
//        Object accessTokenResult;
//        String accessToken = null;
//        if (HttpUtil.isHttp(tokenUrl) || HttpUtil.isHttps(tokenUrl)) {
//            accessTokenResult = restUtilLingXing.lingXingRequest("1", "post", paramsAuth, tokenUrl, null, null);
//            JSONObject jsonObject = (JSONObject) accessTokenResult;
//            if (!"200".equals(jsonObject.get("code"))) {
//                Assert.isTrue(false, "应用 {} 获取AccessToken失败，错误信息 {}", invoke.getAppName(), jsonObject.get("msg"));
//            }
//            //取得access-token
//            accessToken = ((JSONObject) jsonObject.get("data")).get("access_token").toString();
//        } else {
//            Assert.isTrue(false, "应用 {} 请求路径 {} 错误，请检查配置", invoke.getAppName(), tokenUrl);
//        }
//        return accessToken;
    }

    @Override
    public Object invokeFrom(DataContextModel.DatainterfaceFromModel from, JSONObject currentParamsMap, JSONObject currentHeadersMap)   {
        DataContextModel.DatainterfaceAuthorityModel datainterfaceAuthority = from.getAuthority();
        Assert.isTrue(ObjectUtil.isAllNotEmpty(datainterfaceAuthority), "{} 来源接口 {} 金蝶拓展授权信息配置错误，请检查配置", StrUtil.concat(true, from.getTaskCode()), from.getEnCode());
        String appId = common.getAuthoritySimpleFactory(datainterfaceAuthority, "appId");
        String tokenUrl = datainterfaceAuthority.getRootPath();
        String accessToken = StrUtil.toStringOrNull(getAuth(datainterfaceAuthority));
        //获取接口信息
        String requestMethod = from.getRequestMethod();
        String requestUrl = from.getInterfaceUrl();
        if (HttpUtil.isHttp(requestUrl) || HttpUtil.isHttps(requestUrl)) {
            JSONObject params = new JSONObject();
            params.put("access_token", accessToken);
            params.put("app_key", appId);
            params.put("timestamp", System.currentTimeMillis() / 1000);
            Object res;
            try {
                res = restUtilLingXing.lingXingRequest("2", requestMethod, params, requestUrl, currentHeadersMap, currentParamsMap);
            } catch (Exception ex) {
                throw new RuntimeException(StrUtil.format("{} Lingxing目标接口 {} ，执行 {} 操作 {} 发生异常 ", StrUtil.concat(true, from.getTaskCode()), from.getEnCode(), requestUrl, StrUtil.subPre(JsonUtil.getObjectToString(currentParamsMap), 500), ExceptionUtil.getRootCauseMessage(ex)));
            }
            JSONArray jsonToBean = JsonUtil.getJsonToJsonArraySafe(res, "$.data");
            if (CollUtil.isEmpty(jsonToBean)) {
                throw new RuntimeException(StrUtil.concat(true, "拉取失败或无返回值：", StrUtil.subPre(JsonUtil.getObjectToString(res), 500)));
            }
            return jScriptUtil.callJsFrom(from.getDataProcessing(), res == null ? new ArrayList<>() : res, null, null);
        } else {
            Assert.isTrue(false, "{} 来源接口 {} 请求路径 {} 错误，请检查配置", StrUtil.concat(true, from.getTaskCode()), from.getEnCode(), tokenUrl);
        }
        return null;
    }


}
